{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 1024)\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "def img2vector(filename):\n",
    "    returnVect = np.zeros((1,1024))\n",
    "    fr = open(filename)\n",
    "    for i in range(32):\n",
    "        lineStr = fr.readline()\n",
    "        for j in range(32):\n",
    "            returnVect[0,32*i+j] = int(lineStr[j])\n",
    "    return returnVect\n",
    "\n",
    "testVector = img2vector('testDigits/0_13.txt')\n",
    "print(testVector.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "the total number of errors is: 11\n",
      "\n",
      "the total error rate is: 0.011628\n"
     ]
    }
   ],
   "source": [
    "import operator\n",
    "\n",
    "def classify0(inX, dataSet, labels, k):\n",
    "    dataSetSize = dataSet.shape[0]\n",
    "    #❶（以下三行） 距离计算\n",
    "    # np.tile(a,(2,1))就是把a先沿x轴（就这样称呼吧）复制1倍，即没有复制，仍然是 [0,1,2],再把结果沿y方向复制2倍\n",
    "    diffMat = np.tile(inX, (dataSetSize,1)) - dataSet  #np.tile把数组沿各个方向复制\n",
    "    sqDiffMat = diffMat**2\n",
    "    sqDistances = sqDiffMat.sum(axis=1)\n",
    "    distances = sqDistances**0.5\n",
    "    sortedDistIndicies = distances.argsort()\n",
    "    classCount={}\n",
    "    #❷ （以下两行） 选择距离最小的k个点,统计频率\n",
    "    for i in range(k):\n",
    "        voteIlabel = labels[sortedDistIndicies[i]]\n",
    "        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1\n",
    "    #❸ 排序，字典根据词频降序\n",
    "    sortedClassCount = sorted(classCount.iteritems(),key=operator.itemgetter(1), reverse=True)        \n",
    "    return sortedClassCount[0][0]\n",
    "\n",
    "\n",
    "\n",
    "import os\n",
    "def handwritingClassTest():\n",
    "    hwLabels = []\n",
    "    trainingFileList = os.listdir('trainingDigits')           #load the training set\n",
    "    m = len(trainingFileList)\n",
    "    trainingMat = np.zeros((m,1024))\n",
    "    for i in range(m):\n",
    "        fileNameStr = trainingFileList[i]\n",
    "        fileStr = fileNameStr.split('.')[0]     #take off .txt\n",
    "        classNumStr = int(fileStr.split('_')[0])\n",
    "        hwLabels.append(classNumStr)\n",
    "        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)\n",
    "    testFileList = os.listdir('testDigits')        #iterate through the test set\n",
    "    errorCount = 0.0\n",
    "    mTest = len(testFileList)\n",
    "    for i in range(mTest):\n",
    "        fileNameStr = testFileList[i]\n",
    "        fileStr = fileNameStr.split('.')[0]     #take off .txt\n",
    "        classNumStr = int(fileStr.split('_')[0])\n",
    "        vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)\n",
    "        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)\n",
    "        #print \"the classifier came back with: %d, the real answer is: %d\" % (classifierResult, classNumStr)\n",
    "        if (classifierResult != classNumStr): errorCount += 1.0\n",
    "    print \"\\nthe total number of errors is: %d\" % errorCount\n",
    "    print \"\\nthe total error rate is: %f\" % (errorCount/float(mTest))\n",
    "    \n",
    "handwritingClassTest()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
